<template>
  <div class="app-container">
    <!--搜索栏-->
    <div class="filter-container">
      <el-input
        v-model="listQuery.search"
        placeholder="全局搜索"
        style="width: 200px;"
        class="filter-item"
        size="mini"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        size="mini"
        @click="handleFilter"
      >搜索</el-button>
    </div>
    <!--table 表格-->
    <el-table
      v-loading="loadingTableVisible"
      :element-loading-text="loadingTableTitle"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :data="list"
      border
      size="mini"
    >
      <el-table-column label="编号" prop="id" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="名称" prop="name" align="center">
        <template slot-scope="scope">
          <a class="list-a" @click="handleTenantDialog(scope.row.id)">{{ scope.row.name }}</a>
        </template>
      </el-table-column>

       <el-table-column label="域名" prop="domain" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.domain }}</span>
        </template>
      </el-table-column>

      <el-table-column label="手机号码" prop="phoneNumber" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.phoneNumber }}</span>
        </template>
      </el-table-column>

      <el-table-column label="密钥" prop="name" align="center" width="260">
        <template slot-scope="scope">
          <span>{{ scope.row.secretKey }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="emailAddress" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.emailAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" width="150" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建IP地址" prop="creationIP" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.creationIP }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="100">
        <template slot-scope="{row}">
          <!-- <el-button type="primary"  class="list-mini-btn" @click="handleDetail(row)">详情</el-button> -->
          <!-- <el-button type="primary"  class="list-mini-btn" @click="handleResetPwd(row)">重置密码</el-button> -->
          <el-button type="primary" class="list-mini-btn" @click="handleGo(row)">进入系统</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
    />
    <!--详情窗体-->
    <el-dialog :visible.sync="dialogDetailVisible">
      <el-tabs value="info" type="border-card" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="info">
          <el-form label-position="right" label-width="100px">
            <el-form-item label="手机号码：">
              <span>{{temp.phoneNumber}}</span>
            </el-form-item>
            <el-form-item label="名称：">
              <span>{{temp.name}}</span>
            </el-form-item>
            <el-form-item label="密钥：">
              <span>{{temp.secretKey}}</span>
            </el-form-item>
            <el-form-item label="邮箱：">
              <span>{{temp.emailAddress}}</span>
            </el-form-item>
            <el-form-item label="创建时间：">
              <span>{{temp.creationTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
            </el-form-item>
            <el-form-item label="创建IP：">
              <span>{{temp.creationIpAddress}}</span>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="日志跟踪" name="log">
          <el-table
            :data="logData"
            style="width: 100%;font-size:12px;"
            :row-style="{height:'30px'}"
            :cell-style="{padding:'3px'}"
          >
            <el-table-column prop="source" label="来源"></el-table-column>
            <el-table-column prop="level" label="等级"></el-table-column>
            <el-table-column prop="executionDuration" label="执行时长"></el-table-column>
            <el-table-column prop="creationIpAddress" label="客户端IP地址"></el-table-column>
            <el-table-column prop="systemType" label="系统类型"></el-table-column>
            <el-table-column prop="creationTime" label="执行时间"></el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="数据库管理" name="db">
          <el-input placeholder="请输入内容">
            <template slot="prepend">连接字符串</template>
            <el-button slot="append">尝试连接</el-button>
          </el-input>
        </el-tab-pane>
        <el-tab-pane label="权限列表" name="permission">
          <el-tree
            ref="tree"
            class="filter-tree"
            :data="permissionData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            :default-expand-all="true"
          />
        </el-tab-pane>
        <el-tab-pane label="异常警报" name="exception"></el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!--重置密码窗体-->
    <el-dialog :visible.sync="dialogResetVisible" title="重置密码">
      <el-form
        ref="dataForm"
        :rules="pwdRules"
        :model="temp"
        label-position="right"
        label-width="80px"
        class="form-inline"
      >
        <el-form-item label="新密码" prop="password">
          <el-input type="password" v-model="temp.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="temp.confirmPassword" />
        </el-form-item>
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogResetVisible=false">取消</el-button>
          <el-button type="primary" @click="SavePwdData">确认修改</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import waves from "@/directive/waves"; // 按钮波纹
import { parseTime } from "@/utils"; // 工具
import pagination from "@/components/TablePage"; // 分页
import { validPassword } from "@/utils/validate";
import {
  getTenantList,
  getTenantInfo,
  resetPwd,
  login,
  getPermission
} from "@/api/site/tenant";
import { getEnum } from "@/utils/global";
export default {
  name: "tenantList",
  components: { pagination },
  directives: { waves },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error("密码不能为空"));
      } else if (!validPassword(value)) {
        callback(new Error("请输入正确的密码，长度不能小于6位"));
      } else {
        callback();
      }
    };
    return {
      listQuery: {
        // 分页及搜索参数
        page: 1,
        limit: 20,
        search: undefined
      },
      temp: {
        id: undefined,
        password: "",
        confirmPassword: "",
        phoneNumber: "",
        creationTime: "",
        domain: "",
        emailIpAddress: "",
        name: "",
        secretKey: ""
      },
      list: [],
      total: 0,
      loadingTableVisible: true,
      loadingTableTitle: "拼命加载中",
      drawerSettingVisible: false,
      drawerSettingTitle: "",
      dialogDetailVisible: false,
      dialogResetVisible: false,
      pwdRules: {
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      logData: [],
      permissionData: [],
      defaultProps: {
        children: "children",
        label: "displayName",
        id: "name"
      }
    };
  },
  created() {
    this.getTenants();
  },
  methods: {
    // 获取客户列表
    getTenants() {
      this.loadingTableVisible = true;
      getTenantList(this.listQuery)
        .then(response => {
          this.list = response.data.items;
          this.total = response.data.total;
          this.loadingTableVisible = false;
        })
        .catch(() => {
          this.loadingTableVisible = false;
        });
    },
    //监控tab选择事件
    handleClick(tab, event) {
      if (tab.name === "permission") {
        getPermission(this.temp.id).then(response => {
          this.permissionData = response.data.permissions;
        });
      } else if (tab.name === "info") {
        gettenantInfo(this.temp.id).then(response => {
          this.temp = response.data;
        });
      }
      console.log(tab, event);
    },
    // 搜索事件
    handleFilter() {
      this.listQuery.page = 1;
      this.getTenants();
    },
    //详情事件
    handleTenantDialog(row) {
      this.temp.id = row.id;
      this.dialogDetailVisible = true;
      gettenantInfo(this.temp.id).then(response => {
        this.temp = response.data;
      });
    },
    // 设置事件
    handlerSetting(secretKey) {
      this.drawerSettingVisible = true;
    },
    handleGo(row) {
      this.$confirm("确认进入系统？进入后自动退出当前系统", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const loading = this.$loading({ text: "正在登录站点系统" });
        this.$store
          .dispatch("user/tenantLogin", row.id)
          .then(() => {
            this.$router.push({
              path: this.redirect || "/",
              query: this.otherQuery
            });
            location.reload();
            loading.close();
          })
          .catch(() => {
            loading.close();
          });
      });
    },
    handleRefreshCache() {
      this.$confirm("确认刷新Redis缓存？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const loading = this.$loading({ text: "正在刷新缓存" });
          refreshCache()
            .then(response => {
              loading.close();
              this.$message({
                message: response.message,
                type: response.success ? "success" : "error"
              });
            })
            .catch(() => {
              loading.close();
            });
        })
        .catch(error => {
          console.error(error);
        });
    },
    // 关闭设置窗体
    handleSettingClose(done) {
      done();
    },
    // 转换到期天数
    paramTimeConvertDay(date) {
      var startDate = new Date();
      var endDate = new Date(date);
      var days = endDate.getTime() - startDate.getTime();
      var day = parseInt(days / (1000 * 60 * 60 * 24));
      return day;
    },
    //修改密码窗体事件
    handleResetPwd(row) {
      this.dialogResetVisible = true;
      this.temp.userId = row.id;
    },
    //保存修改密码事件
    SavePwdData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const loading = this.$loading({ text: "正在修改密码" });
          resetPwd(this.temp)
            .then(response => {
              loading.close();
              this.$message({
                message: response.message,
                type: response.success ? "success" : "error"
              });
              this.dialogResetVisible = false;
            })
            .catch(() => {
              loading.close();
            });
        } else return false;
      });
    }
  }
};
</script>
